const db = require('../config/db');
const bcrypt = require('bcryptjs');
const crypto = require('crypto');

async function encryptPassword(password) {
  // 1. SHA-256哈希
  const sha256Hash = crypto.createHash('sha256')
    .update(password)
    .digest('hex');

  // 2. Bcrypt加密
  return bcrypt.hash(sha256Hash, 10);
}

class StudentModel {
  // 根据学号获取学生
  static async getStudentByNumber(studentNumber) {
    const [students] = await db.query(
      `SELECT * FROM students WHERE s_no = ?`,
      [studentNumber]
    );
    return students[0];
  }

  // 创建学生
  static async createStudent(studentData) {
    const { s_no, s_name, class: className, enrollment_year=null } = studentData;

    let enrollmentYear = enrollment_year;
    if (!enrollment_year) {
      // 获取学号的前两位作为enrollment_year的后两位
      // 当前年份的前两位作为enrollment_year的前两位
      const currentYear = new Date().getFullYear().toString();
      const yearPrefix = currentYear.slice(0, 2); // 当前年份前两位
      const yearSuffix = s_no.slice(0, 2); // 学号前两位
      enrollmentYear = parseInt(yearPrefix + yearSuffix, 10);
    }

    const encryptedPassword = await encryptPassword('password123');
    const [result] = await db.query(
      `INSERT INTO students 
       (s_no, s_name, password, class, enrollment_year) 
       VALUES (?, ?, ?, ?, ?)`,
      [s_no, s_name, encryptedPassword, className, enrollmentYear]
    );

    return { id: result.insertId, ...studentData };
  }
}

module.exports = StudentModel;